<template>
  <div class="page-card">
    <div class="table-toolbar">
      <div>
        <div class="page-header__title">角色管理</div>
        <div class="page-header__desc">配置系统角色及可用状态</div>
      </div>
      <el-button type="primary" @click="openDialog()">
        <el-icon><Plus /></el-icon>
        新建角色
      </el-button>
    </div>

    <el-table :data="roles" border v-loading="loading">
      <el-table-column prop="role_code" label="角色编码" width="160" />
      <el-table-column prop="role_name" label="角色名称" width="160" />
      <el-table-column prop="role_desc" label="角色描述" min-width="200" />
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="openDialog(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="pagination.size"
        :current-page="pagination.page"
        :total="pagination.total"
        @current-change="handlePageChange"
      />
    </div>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="460px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="角色编码" prop="role_code">
          <el-input v-model="form.role_code" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="角色名称" prop="role_name">
          <el-input v-model="form.role_name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="role_desc">
          <el-input v-model="form.role_desc" type="textarea" rows="2" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { createRole, deleteRole, getRoleList, updateRole } from '@/api/system'
import type { Role } from '@/types/system'

const loading = ref(false)
const saving = ref(false)
const roles = ref<Role[]>([])
const pagination = reactive({ page: 1, size: 10, total: 0 })

const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()
const form = reactive({
  id: 0,
  role_code: '',
  role_name: '',
  role_desc: '',
  status: 1
})

const rules: FormRules = {
  role_code: [{ required: true, message: '请输入角色编码', trigger: 'blur' }],
  role_name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
}

const dialogTitle = computed(() => (isEdit.value ? '编辑角色' : '新建角色'))

const loadRoles = async () => {
  loading.value = true
  try {
    const skip = (pagination.page - 1) * pagination.size
    const res = await getRoleList({ skip, limit: pagination.size })
    roles.value = res.items
    pagination.total = res.total
  } catch (error: any) {
    ElMessage.error(error?.message || '加载角色失败')
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page: number) => {
  pagination.page = page
  loadRoles()
}

const resetForm = () => {
  Object.assign(form, {
    id: 0,
    role_code: '',
    role_name: '',
    role_desc: '',
    status: 1
  })
  formRef.value?.clearValidate()
}

const openDialog = (row?: Role) => {
  resetForm()
  if (row) {
    isEdit.value = true
    Object.assign(form, row)
  } else {
    isEdit.value = false
  }
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  saving.value = true
  try {
    if (isEdit.value) {
      await updateRole(form.id, {
        role_code: form.role_code,
        role_name: form.role_name,
        role_desc: form.role_desc,
        status: form.status
      })
    } else {
      await createRole({
        role_code: form.role_code,
        role_name: form.role_name,
        role_desc: form.role_desc,
        status: form.status
      })
    }
    ElMessage.success('操作成功')
    dialogVisible.value = false
    loadRoles()
  } catch (error: any) {
    ElMessage.error(error?.message || '保存失败')
  } finally {
    saving.value = false
  }
}

const handleDelete = async (row: Role) => {
  await ElMessageBox.confirm(`确认删除角色【${row.role_name}】吗？`, '提示', {
    type: 'warning'
  })
  try {
    await deleteRole(row.id)
    ElMessage.success('已删除')
    loadRoles()
  } catch (error: any) {
    ElMessage.error(error?.message || '删除失败')
  }
}

onMounted(loadRoles)
</script>

<style scoped lang="scss">
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: var(--spacing-md);
}
</style>
